package com.example.hfweather.ui.detail

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import com.example.hfweather.R
import com.example.hfweather.adapter.WeatherIndexAdapter
import com.example.hfweather.base.BaseBindingActivity
import com.example.hfweather.bean.CityData
import com.example.hfweather.databinding.AcWeatherDetailBinding
import com.example.hfweather.ui.map.MapActivity
import com.example.hfweather.ui.video.Media3PlayerActivity
import com.example.hfweather.util.FavoriteManager
import com.example.hfweather.util.GridSpacingItemDecoration
import com.example.hfweather.util.WeatherUtils
import com.qweather.sdk.response.indices.IndicesDailyResponse
import com.qweather.sdk.response.weather.WeatherDaily

class WeatherDetailActivity : BaseBindingActivity<AcWeatherDetailBinding>(),
    WeatherDetailView{

    //接收参数定义属性
    private var cityName = ""
    private var latitude = ""
    private var longitude= ""
    private var weather= ""
    private var temperature= ""

    /**
     * 设置天气和温度
     */
    fun setWeatherAndTemperature(weather: String, temperature: String) {
        this.weather = weather
        this.temperature = temperature
    }


    private var mPresenter: WeatherDetailPresenter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mPresenter = WeatherDetailPresenter(this, WeatherDetailInteractor())
        //接收参数
        getParamFormIntent()
        //2.获取天气数据
        getWeatherData()
        // 3. 初始化宫格布局视图
        initView()
        //4.设置点击事件
        setOnClickEvents()
        //5.查询当前城市是否收藏并刷新收藏按钮
        refreshFavoriteIcon(FavoriteManager.isFavorite(cityName))

    }

    override fun onResume() {
        super.onResume()
        getWeatherData()
    }

   // 1.接收参数
    private fun getParamFormIntent() {
        cityName = intent.getStringExtra("cityName") ?: ""
        latitude = intent.getStringExtra("latitude") ?: ""
        longitude = intent.getStringExtra("longitude") ?: ""
        mPresenter?.setCityName(cityName)
        mPresenter?.setLocation(latitude, longitude)
       binding.detailTodayCard.tvCityName.text = cityName

    }
    //2.获取天气数据
    private fun getWeatherData() {
        showLoading()
        mPresenter?.get3DayWeather()
        mPresenter?.getTodayIndices()

    }

    /**
     * 3. 初始化view
     */
    fun initView() {
        binding.detailTodayCard.rvWeatherOthers.layoutManager = GridLayoutManager(this, 2)
        binding.detailTodayCard.rvWeatherOthers.addItemDecoration(
            GridSpacingItemDecoration(
                2,
                WeatherUtils.dip2px(this, 10f), false
            )
        )
        binding.detailTodayCard.rvWeatherOthers.adapter = WeatherIndexAdapter()
    }
    /**
     * 4.设置点击事件
     */
    private fun setOnClickEvents() {
        //跳转视频播放页面播放视频
        binding.detailTodayCard.ivVideoIcon.setOnClickListener {
            //跳转Media3PlayerActivity播放视频
            val intent = Intent(this, Media3PlayerActivity::class.java)
            startActivity(intent)
        }

        //跳转到地图页面
        binding.detailTodayCard.ivLocationIcon.setOnClickListener {
            val intent = Intent(this, MapActivity::class.java)
            intent.putExtra("cityName", cityName)
            intent.putExtra("latitude", latitude)
            intent.putExtra("longitude", longitude)
            startActivity(intent)

        }

        binding.detailTodayCard.ivDetailStarCity.setOnClickListener {
            //切换收藏状态
            val isNowFavorite = FavoriteManager.toggleFavorite(CityData(cityName,longitude.toDouble(),latitude.toDouble(),weather,temperature))
            //刷新收藏图标
            refreshFavoriteIcon(isNowFavorite)
            if (isNowFavorite) {
                Toast.makeText(this, "已收藏", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "已取消收藏", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 刷新收藏爱心
     */
    private fun refreshFavoriteIcon(isStart: Boolean) {
        if (isStart) {
            binding.detailTodayCard.ivDetailStarCity.setImageResource(R.mipmap.icon_stared)
        } else {
            binding.detailTodayCard.ivDetailStarCity.setImageResource(R.mipmap.icon_detail_star)
        }
    }

    override fun initBinding(layoutInflater: LayoutInflater): AcWeatherDetailBinding {
        return AcWeatherDetailBinding.inflate(layoutInflater)
    }

    @SuppressLint("SetTextI18n")
    override fun refreshTodayDataSuccess(weather: WeatherDaily) {
        hideLoading()

        binding.detailTodayCard.llCurrentWeatherContainer.visibility = View.VISIBLE

        val todayTemp = weather.tempMin + "° / " + weather.tempMax + "°"
        binding.detailTodayCard.tvTemperature.text = todayTemp

        // mPresenter?.setWeatherAndTemperature(weather.textDay, todayTemp)

        //白天、夜间天气
        refreshDayNightMoonPhase(weather)

        //湿度、紫外线强度指数、气压
        binding.detailTodayCard.humidityUvPressure.tvName1.text = "湿度"
        binding.detailTodayCard.humidityUvPressure.tvValue1.text = weather.humidity
        binding.detailTodayCard.humidityUvPressure.tvName2.text = "紫外线强度指数"
        binding.detailTodayCard.humidityUvPressure.tvValue2.text = weather.uvIndex
        binding.detailTodayCard.humidityUvPressure.tvName3.text = "气压"
        binding.detailTodayCard.humidityUvPressure.tvValue3.text = weather.pressure + "hPa"

        //日降水量，能见度
        binding.detailTodayCard.rainVisContainer.tvName1.text = "日降水量"
        binding.detailTodayCard.rainVisContainer.tvValue1.text = weather.precip + " mm"
        binding.detailTodayCard.rainVisContainer.tvName2.text = "能见度"
        binding.detailTodayCard.rainVisContainer.tvValue2.text = weather.vis + "km"
        binding.detailTodayCard.rainVisContainer.tvName3.text = ""
        binding.detailTodayCard.rainVisContainer.tvValue3.text = ""


        //日出日落
        binding.detailTodayCard.tvSunriseSunset.text =
            "日出时间：" + weather.sunrise + " 日落时间：" + weather.sunset
        //月出月落
        binding.detailTodayCard.tvMoonriseMoonset.text =
            "月出时间：" + weather.moonrise + " 月落时间：" + weather.moonset
        //风况
        binding.detailTodayCard.tvDayWindNightWind.text =
            "白天风况：" + weather.windDirDay + weather.windScaleDay + "级 风速：" + weather.windSpeedDay + "km/h\n夜间风况：" + weather.windDirNight + weather.windScaleNight + "级 风速：" + weather.windSpeedNight + "km/h"

    }

    /**
     * 刷新白天、夜间天气, 月相
     */
    fun refreshDayNightMoonPhase(weather: WeatherDaily) {
        binding.detailTodayCard.weatherMoonPhase.tvName1.text = "白天天气"
        binding.detailTodayCard.weatherMoonPhase.tvValue1.text = weather.textDay
        val textDayIconCode = "_" + weather.iconDay.replace("-", "_")
        if (WeatherUtils.isDrawableInRClass(this, textDayIconCode)) {
            val drawable = WeatherUtils.getDrawableByName(this, textDayIconCode)
            drawable?.let {
                binding.detailTodayCard.weatherMoonPhase.ivIcon1.setImageDrawable(drawable)
            }
            binding.detailTodayCard.weatherMoonPhase.ivIcon1.visibility = View.VISIBLE
        } else {
            binding.detailTodayCard.weatherMoonPhase.ivIcon1.visibility = View.GONE
        }

        binding.detailTodayCard.weatherMoonPhase.tvName2.text = "夜间天气"
        binding.detailTodayCard.weatherMoonPhase.tvValue2.text = weather.textNight
        val textNightIconCode = "_" + weather.iconNight.replace("-", "_")
        if (WeatherUtils.isDrawableInRClass(this, textNightIconCode)) {
            val drawable = WeatherUtils.getDrawableByName(this, textNightIconCode)
            drawable?.let {
                binding.detailTodayCard.weatherMoonPhase.ivIcon2.setImageDrawable(drawable)
            }
            binding.detailTodayCard.weatherMoonPhase.ivIcon2.visibility = View.VISIBLE
        } else {
            binding.detailTodayCard.weatherMoonPhase.ivIcon2.visibility = View.GONE
        }

        binding.detailTodayCard.weatherMoonPhase.tvName3.text = "月相"
        binding.detailTodayCard.weatherMoonPhase.tvValue3.text = weather.moonPhase

        val moonPhaseIconCode = "_" + weather.moonPhaseIcon.replace("-", "_")
        if (WeatherUtils.isDrawableInRClass(this, moonPhaseIconCode)) {
            val drawable = WeatherUtils.getDrawableByName(this, moonPhaseIconCode)
            drawable?.let {
                binding.detailTodayCard.weatherMoonPhase.ivIcon3.setImageDrawable(drawable)
            }
            binding.detailTodayCard.weatherMoonPhase.ivIcon3.visibility = View.VISIBLE
        } else {
            binding.detailTodayCard.weatherMoonPhase.ivIcon3.visibility = View.GONE
        }
    }

    override fun refreshTodayDataFail(error: String) {
        hideLoading()
    }

    @SuppressLint("SetTextI18n")
    override fun refreshOther2DaysSuccess(
        weather: WeatherDaily,
        weather2: WeatherDaily
    )  {
        hideLoading()
        //刷新第一天
        binding.detailTwoDaysCard.tvTomorrowTemperature.text =
            weather.tempMin + "°/" + weather.tempMax + "°"
        binding.detailTwoDaysCard.tvTomorrowWeather.text = weather.textDay
        val textDayIconCode = "_" + weather.iconDay.replace("-", "_")
        if (WeatherUtils.isDrawableInRClass(this, textDayIconCode)) {
            val drawable = WeatherUtils.getDrawableByName(this, textDayIconCode)
            drawable?.let {
                binding.detailTwoDaysCard.ivTomorrowWeatherIcon.setImageDrawable(drawable)
            }
            binding.detailTwoDaysCard.ivTomorrowWeatherIcon.visibility = View.VISIBLE
        } else {
            binding.detailTwoDaysCard.ivTomorrowWeatherIcon.visibility = View.GONE
        }

        //刷新第二天
        binding.detailTwoDaysCard.tvDayAfterTemperature.text =
            weather2.tempMin + "°/" + weather2.tempMax + "°"
        binding.detailTwoDaysCard.tvDayAfterWeather.text = weather2.textDay
        val textDayIconCode2 = "_" + weather2.iconDay.replace("-", "_")
        if (WeatherUtils.isDrawableInRClass(this, textDayIconCode2)) {
            val drawable = WeatherUtils.getDrawableByName(this, textDayIconCode2)
            drawable?.let {
                binding.detailTwoDaysCard.ivDayAfterWeatherIcon.setImageDrawable(drawable)
            }
            binding.detailTwoDaysCard.ivDayAfterWeatherIcon.visibility = View.VISIBLE
        } else {
            binding.detailTwoDaysCard.ivDayAfterWeatherIcon.visibility = View.GONE
        }
    }
    override fun refreshOther2DaysFail(error: String) {
        hideLoading()
    }

    /**
     * 今日生活指数数据刷新成功时调用
     * @param weather 指数数据响应对象
     */
    override fun refreshTodayIndicesSuccess(weather: IndicesDailyResponse) {
        hideLoading()

        //刷新天气指数
        val list = weather.daily
        if (list != null && list.isNotEmpty()) {
            val adapter = binding.detailTodayCard.rvWeatherOthers.adapter as WeatherIndexAdapter
            adapter.submitList(list)
        }
    }

    /**
     * 今日生活指数数据刷新失败时调用
     * @param error 错误信息
     */
    override fun refreshTodayIndicesFailure(error: String) {
        hideLoading()
    }


}